import React from 'react';
import { StyleSheet, Text, View, TouchableHighlight, StatusBar } from 'react-native';
import NumBtn from './NumBtn';

const operChar = ['+', '-', '*', '/'];

export default class App extends React.Component {
  constructor() {
    super();

    this.state = {
      show: true,
      val: [0],
      logs: [],
      results: [],
      result: null
    };

    this.press = this.press.bind(this);

  }

  press(inputVal) {
    let { val, result, logs } = this.state;
    let initiative = [0];
    switch (inputVal) {
      case 'clear':
        this.changeState({ val: initiative, result: null, logs: [], results: [] });
        break;
      case 'back':
        val.pop();
        if (val.length === 0) {
          if (logs.length > 0) {
            val = logs.pop();
          } else {
            val = initiative;
          }
        }
        this.changeState({ val });
        this.calc();
        break;
      case '+':
      case '-':
      case '*':
      case '/':
        if (val.length > 1 || !this.isOperChar(val[0])) {
          logs.push(val);
        }
        val = [inputVal];
        this.changeState({ val });
        break;
      default:
        if (val.length >= 15) {
          return;
        }
        if (result === null) {
          val = [];
        }
        val.push(inputVal);
        this.changeState({ val });
        console.log(this.state.val);
        this.calc();
    }

  }

  calc() {
    let { val, logs, results } = this.state;
    let result = 0;
    logs.forEach(log => {
      result = this.parseVal(log, result);
    });
    result = this.parseVal(val, result);
    // console.log(val);
    this.changeState({
      result
    });
  }

  parseVal(arr, baseVal) {
    if (arr.length === 0) {
      return 0;
    }
    let oper = arr[0];
    if (this.isOperChar(oper)) {
      return new Function(`return ${baseVal}${oper}(${arr.slice(1).join('') || 0})`)();
    } else {
      return arr.join('');
    }
  }

  isOperChar(txt) {
    return operChar.indexOf(txt) !== -1;
  }

  changeState(data) {
    this.setState(state => {
      return { ...state, ...data };
    });
  }

  render() {
    let show = this.state.show;
    return (
      <View style={styles.container}>
        <StatusBar barStyle="dark-content" />
        <View style={styles.top}>
          <View style={styles.logs}>
            {
              this.state.logs.map(log => (<Text key={log} style={styles.log}>{log}</Text>))
            }
          </View>
          <View>
            <Text style={[styles.currentNum, { fontSize: this.state.val.length >= 10 ? (15 - this.state.val.length) * 4 + 40 : 60 }]}>{this.state.val.join('')}</Text>
          </View>
          <View style={styles.result}>
            <Text style={styles.log}>
              {this.state.result === null ? '' : `=${this.state.result}`}
            </Text>
          </View>
        </View>
        <View style={styles.bottom}>
          <View style={styles.col}>
            <NumBtn label="⊙" value="clear" onPress={this.press} textStyles={{ color: '#f8782d' }} />
            <NumBtn label="7" onPress={this.press} />
            <NumBtn label="4" onPress={this.press} />
            <NumBtn label="1" onPress={this.press} />
            <NumBtn label="%" onPress={this.press} />
          </View>
          <View style={styles.col}>
            <NumBtn label="←" value="back" onPress={this.press} />
            <NumBtn label="8" onPress={this.press} />
            <NumBtn label="5" onPress={this.press} />
            <NumBtn label="2" onPress={this.press} />
            <NumBtn label="0" onPress={this.press} />
          </View>
          <View style={styles.col}>
            <NumBtn label="÷" value="/" onPress={this.press} />
            <NumBtn label="9" onPress={this.press} />
            <NumBtn label="6" onPress={this.press} />
            <NumBtn label="3" onPress={this.press} />
            <NumBtn label="." onPress={this.press} />
          </View>
          <View style={[styles.col, { borderRightWidth: 0 }]}>
            <NumBtn label="×" value="*" onPress={this.press} />
            <NumBtn label="－" value="-" onPress={this.press} />
            <NumBtn label="＋" value="+" onPress={this.press} />
            <TouchableHighlight style={[styles.cell, { flex: 2, backgroundColor: '#f8782d', borderTopColor: '#f8782d' }]} underlayColor="#dc6b29" onPress={() => { this.press('AC') }}>
              <Text style={[styles.txt, { color: '#fff' }]}>=</Text>
            </TouchableHighlight>
          </View>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    flexDirection: 'column'
  },
  top: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'flex-end',
    alignItems: 'flex-end',
    paddingRight: 20,
    paddingBottom: 15
  },
  bottom: {
    flex: 1,
    flexDirection: 'row',
  },
  col: {
    flex: 1,
    width: 150,
    flexDirection: 'column',
    borderRightColor: '#ccc',
    borderRightWidth: 1,
    borderStyle: 'solid'
  },
  cell: {
    flex: 1,
    borderTopColor: '#ccc',
    borderTopWidth: 1,
    borderStyle: 'solid',
    justifyContent: 'center',
    alignItems: 'center'
  },
  txt: {
    fontSize: 30,
    color: '#51545b'
  },
  currentNum: {
    fontSize: 60,
    color: '#51545b'
  },
  result: {
    height: 40
  },
  log: {
    color: '#ccc',
    fontSize: 30
  }
});
